from sqlalchemy import create_engine
from sqlalchemy import inspect


import logging as log


def get_conneaction(db_config):
    log.info(db_config)
    """
    获取数据库连接
    :param db_config: 数据库配置信息
    :return: 数据库连接
    """
    connection_string = f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['dbname']}"
    # 创建DBTool实例
    engine = create_engine(connection_string)
    return engine


def get_all_tables(engine):
    with engine.connect() as conn:
        inspector = inspect(conn)
        tables = inspector.get_table_names()
    return tables


def get_table_columns(engine, table_name):
    """获取指定表的所有字段信息"""
    with engine.connect() as conn:
        inspector = inspect(conn)  # 使用 inspect 而不是 Inspector.from_engine
        columns = inspector.get_columns(table_name)
    return columns



# 使用示例
if __name__ == "__main__":
    # 从配置文件读取数据库连接信息
    # 这里假设你已经按照前面的步骤配置好了数据库连接字符串
    db_config = {
        'host': 'localhost',
        'port': 3306,
        'user': 'root',
        'password': '123456',
        'dbname': 'gfast'
    }
    connection_string = f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['dbname']}"

    # 创建DBTool实例
    engine = create_engine(connection_string)

    # 获取所有表名
    all_tables = get_all_tables(engine)
    print("所有表名:", all_tables)

    # 假设你想获取名为'your_table_name'的表的字段信息
    table_name = 'cts_voice'
    columns = get_table_columns(engine,table_name)
    print(f"表 {table_name} 的字段信息:")
    for column in columns:
        print(f"字段名: {column['name']}, 数据类型: {column['type']}, 可否为空: {column['nullable']}")
